package com.hongdee.scm.approvalflow.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.approvalflow.dao.ITScmApprovalDetailDao;
import com.hongdee.scm.approvalflow.entity.TScmApprovalflowDetail;
import com.hongdee.scm.approvalflow.service.ITScmApprovalflowDetailService;
import com.hongdee.scm.approvalflow.service.ITScmApprovalflowService;
import com.hongdee.scm.common.service.ICommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 名  称:TScmApprovalflowDetailServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.scm.approvalflow.service.impl
 * 作  者: 术洪超
 * 日  期:2017-06-19 19:03
 */
@Service
public class TScmApprovalflowDetailServiceImpl implements ITScmApprovalflowDetailService {

    @Autowired
    private ITScmApprovalDetailDao itScmApprovalDetailDao;
    @Autowired
    private ICommonService common;
    @Autowired
    private ITScmApprovalflowService itScmApprovalflowService;

    private String tabName="T_SCM_APPROVALFLOW_DETAIL";

    //保存审批详情的过程,并修改

    @Override
    public Map save(TScmApprovalflowDetail data, String approvalflowPId, String uid) throws Exception {

        if(this.itScmApprovalDetailDao.list("select r_id from t_bc_role_user where u_id =? and r_id in " +
                " ( select start_roles from t_scm_approvalflow where start_status in ( select current_approval_status" +
                " from t_scm_allocation_order where id=? ) and approvalflow_p_id =? and status ='1' and company_id=?)",uid,data.getAllocationId(),approvalflowPId,TokenUtil.getCompanyId(uid)).size()<0){
            throw new Exception("已经审批过！");
        }
        if (data.getId() == null) {
            data.setCreateUser(uid);
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());

        } else {
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
        }
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        data.setApprovalDate(format.format(date));
        data.setCompanyId(TokenUtil.getCompanyId(uid));
        data.setApprovaler(uid);

        this.itScmApprovalDetailDao.saveOrUpdate(data);

        //获取初始状态
        Map currentApprovalStatus = this.currentApprovalStatus(data.getAllocationId());
        //当前流转状态
        Map circulationStatus = this.circulationStatus(approvalflowPId, currentApprovalStatus.get("currentApprovalStatus").toString(),uid);
        if(circulationStatus.size()>0){
            //修改调拨单状态
            this.update(data.getAllocationId(), circulationStatus.get("circulationStatus").toString());
        } else{
            throw new Exception("审批结束");
        }
        //当审批结束，更新调拨审批完成时间
        List tempParam = new ArrayList();
        tempParam.add(currentApprovalStatus.get("currentApprovalStatus"));
        tempParam.add(data.getAllocationId());
        tempParam.add(TokenUtil.getCompanyId(uid));
        if(this.itScmApprovalDetailDao.info("select * from T_SCM_APPROVALFLOW where status = '1' and start_status = ? " +
                " and approvalflow_p_id in (select allocation_type from " +
                " t_scm_allocation_order where id = ? ) and company_id=?",tempParam.toArray()).get("circulationStatus").equals("结束")){
            Date d = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            this.itScmApprovalDetailDao.executeSQL("update t_scm_allocation_order set finish_date = ? " +
                    " where id = ? ",df.format(d),data.getAllocationId());
        }
//        if(data.getApprovalStatus().equals("结束")){
//            Date d = new Date();
//            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            this.itScmApprovalDetailDao.executeSQL("update t_scm_allocation_order set finish_date = ? " +
//                    " where id = ? ",df.format(d),data.getAllocationId());
//        }
        //个推
        Map map = new HashMap();
         if("结束".equals(currentApprovalStatus.get("currentApprovalStatus"))){
            map.put("no","1");
         }else{
             map = itScmApprovalflowService.pushMessage(approvalflowPId,data.getAllocationId(),uid,circulationStatus.get("circulationStatus").toString());
         }
        return map;
    }


    //查询审批流程的当前节点通过以后状态
    private Map circulationStatus(String approvalflowPId, String startStatus,String uid) throws Exception {
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from t_scm_approvalflow where status= '1' and company_id=?");
        params.add(TokenUtil.getCompanyId(uid));
        if (!StringUtils.isEmpty(approvalflowPId)) {
            sql.append(" and approvalflow_p_id = ?");
            params.add(approvalflowPId);
        }
        if (!StringUtils.isEmpty(startStatus)) {
            sql.append(" and start_status = ?");
            params.add(startStatus);
        }

        Map map = this.itScmApprovalDetailDao.info(sql.toString(), params.toArray());
       /* if(map.size()>0){
            this.update(map.get("id").toString(), map.get("circulationStatus").toString());
        }
*/      return map;

    }


    //修改调拨单的流转状态
    private void update(String id, String status) throws Exception {
        Boolean hasWhere = false;
        Map params = new HashMap();
        StringBuffer hql = new StringBuffer();
        hql.append("update TScmAllocationOrder set currentApprovalStatus = :status");
        params.put("status", status);
        if (!StringUtils.isEmpty(id)) {
            hasWhere = common.appendWhereIfNeed(hql, hasWhere);
            hql.append(" id = :id");
            params.put("id", id);
        }
        this.itScmApprovalDetailDao.update(hql.toString(), params);

    }

    //获取调拨单起始状态,调拨单id
    private Map currentApprovalStatus(String id) throws Exception {
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        sql.append("select current_approval_status from t_scm_allocation_order where id = ? ");
        params.add(id);

        return this.itScmApprovalDetailDao.info(sql.toString(), params.toArray());
    }

    @Override
    public void submit(String id, String status) throws Exception {

        Map params = new HashMap();
        StringBuffer sql = new StringBuffer();
        sql.append("update TScmAllocationOrder set currentApprovalStatus = :status where id =:id");

        params.put("status", status);


        params.put("id", id);
        this.itScmApprovalDetailDao.update(sql.toString(), params);
    }

    /**
     * 审批明细分页
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map page(Map data, String start, String limit, String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select p.*,tbu.u_name approvalers from " + tabName + " p left join " +
                " t_bc_user tbu on tbu.id = p.approvaler where p.company_id = ?");
        params.add(TokenUtil.getCompanyId(uid));
        if(data.get("allocationId")!=null&&!StringUtils.isEmpty(data.get("allocationId"))){
            sql.append(" and allocation_id = ? ");
            params.add(data.get("allocationId"));
        }
        sql.append(" order by p.create_time desc");
        return this.itScmApprovalDetailDao.page(sql.toString(), params.toArray(), start, limit);
    }
}
